<template>
  <div class="message-list">
    <el-card class="message-card">
      <template #header>
        <div class="card-header">
          <MessageSearch
            ref="searchRef"
            :immediate="true"
            @search="handleSearch"
          />
        </div>
      </template>

      <el-table
        :data="messageList"
        border
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="scope">
            <div class="message-title">
              <el-tag
                :type="getMessageTypeTag(scope.row.type)"
                size="small"
                class="message-type"
              >
                {{ getMessageTypeLabel(scope.row.type) }}
              </el-tag>
              <span
                class="title-text"
                v-html="highlightText(scope.row.title, searchQuery)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="handler" label="处理人" width="120" />
        <el-table-column prop="handleTime" label="处理时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              type="primary"
              link
              @click="handleProcess(scope.row)"
              v-if="scope.row.status === 'pending'"
            >处理</el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="消息详情"
      width="800px"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-header">
          <div class="title-section">
            <h3 v-html="highlightText(currentMessage.title, searchQuery)" />
            <div class="meta-info">
              <el-tag
                :type="getMessageTypeTag(currentMessage.type)"
                size="small"
              >
                {{ getMessageTypeLabel(currentMessage.type) }}
              </el-tag>
              <el-tag
                :type="getStatusType(currentMessage.status)"
                size="small"
                class="status-tag"
              >
                {{ getStatusLabel(currentMessage.status) }}
              </el-tag>
            </div>
          </div>
          <div class="creator-info">
            <span>创建人：{{ currentMessage.creator }}</span>
            <span>创建时间：{{ currentMessage.createTime }}</span>
          </div>
        </div>
        <div class="detail-content">
          <div
            class="content-text"
            v-html="highlightText(currentMessage.content, searchQuery)"
          />
        </div>
        <div class="detail-footer">
          <div class="handler-info" v-if="currentMessage.handler">
            <span>处理人：{{ currentMessage.handler }}</span>
            <span>处理时间：{{ currentMessage.handleTime }}</span>
          </div>
          <div class="process-records" v-if="processRecords.length > 0">
            <h4>处理记录</h4>
            <el-timeline>
              <el-timeline-item
                v-for="record in processRecords"
                :key="record.id"
                :type="getTimelineItemType(record.status)"
                :timestamp="record.createTime"
              >
                <div class="record-content">
                  <div class="record-status">
                    <el-tag :type="getStatusType(record.status)" size="small">
                      {{ getStatusLabel(record.status) }}
                    </el-tag>
                  </div>
                  <div class="record-comment" v-if="record.comment">
                    {{ record.comment }}
                  </div>
                  <div class="record-operator">
                    操作人：{{ record.operator }}
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 消息处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理消息"
      width="600px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="processForm.status" placeholder="请选择处理状态">
            <el-option
              v-for="status in processStatus"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理意见" prop="comment">
          <el-input
            v-model="processForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入处理意见"
          />
        </el-form-item>
        <el-form-item label="下一处理人" prop="nextHandler" v-if="processForm.status === 'processing'">
          <el-select
            v-model="processForm.nextHandler"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            placeholder="请选择下一处理人"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            >
              <span>{{ user.name }}</span>
              <span class="user-department">{{ user.department }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import MessageSearch from '@/components/message/SearchBar.vue'
import {
  getMessageList,
  getMessageDetail,
  deleteMessage,
  processMessage,
  getProcessRecords,
  searchUsers
} from '@/api/message'

// 搜索相关
const searchRef = ref(null)
const searchQuery = ref('')

// 数据加载状态
const loading = ref(false)
const submitting = ref(false)
const userSearchLoading = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 列表数据
const messageList = ref([])
const userOptions = ref([])

// 对话框显示状态
const detailDialogVisible = ref(false)
const processDialogVisible = ref(false)

// 当前消息
const currentMessage = ref(null)
const processRecords = ref([])

// 表单引用
const processFormRef = ref(null)

// 处理表单
const processForm = reactive({
  id: '',
  status: '',
  comment: '',
  nextHandler: ''
})

// 表单验证规则
const processRules = {
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  comment: [{ required: true, message: '请输入处理意见', trigger: 'blur' }],
  nextHandler: [{ required: true, message: '请选择下一处理人', trigger: 'change' }]
}

// 处理状态
const processStatus = [
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'rejected', label: '已驳回' },
  { value: 'cancelled', label: '已取消' }
]

// 初始化数据
onMounted(() => {
  fetchMessageList()
})

// 获取消息列表
const fetchMessageList = async (params = {}) => {
  loading.value = true
  try {
    const queryParams = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...params
    }
    const res = await getMessageList(queryParams)
    messageList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = (params) => {
  searchQuery.value = params.query
  pageNum.value = 1
  fetchMessageList(params)
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchMessageList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchMessageList()
}

// 查看消息详情
const handleView = async (row) => {
  try {
    const res = await getMessageDetail(row.id)
    currentMessage.value = res.data
    const recordsRes = await getProcessRecords(row.id)
    processRecords.value = recordsRes.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取消息详情失败:', error)
    ElMessage.error('获取消息详情失败')
  }
}

// 处理消息
const handleProcess = (row) => {
  Object.assign(processForm, {
    id: row.id,
    status: '',
    comment: '',
    nextHandler: ''
  })
  processDialogVisible.value = true
}

// 删除消息
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该消息吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMessage(row.id)
      ElMessage.success('删除成功')
      fetchMessageList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 搜索用户
const searchUsers = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      const res = await searchUsers({ query })
      userOptions.value = res.data
    } catch (error) {
      console.error('搜索用户失败:', error)
    } finally {
      userSearchLoading.value = false
    }
  } else {
    userOptions.value = []
  }
}

// 提交处理
const submitProcess = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    submitting.value = true
    
    await processMessage(processForm)
    ElMessage.success('处理成功')
    processDialogVisible.value = false
    fetchMessageList()
  } catch (error) {
    console.error('处理失败:', error)
    ElMessage.error(error.message || '处理失败')
  } finally {
    submitting.value = false
  }
}

// 工具函数
const getMessageTypeTag = (type) => {
  const typeMap = {
    notification: 'info',
    task: 'warning',
    warning: 'danger',
    system: 'success'
  }
  return typeMap[type] || ''
}

const getMessageTypeLabel = (type) => {
  const labelMap = {
    notification: '通知',
    task: '任务',
    warning: '警告',
    system: '系统'
  }
  return labelMap[type] || type
}

const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    processing: 'primary',
    completed: 'success',
    rejected: 'danger',
    cancelled: 'warning'
  }
  return typeMap[status] || ''
}

const getStatusLabel = (status) => {
  const labelMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    rejected: '已驳回',
    cancelled: '已取消'
  }
  return labelMap[status] || status
}

const getTimelineItemType = (status) => {
  const typeMap = {
    pending: 'info',
    processing: 'primary',
    completed: 'success',
    rejected: 'danger',
    cancelled: 'warning'
  }
  return typeMap[status] || ''
}

// 高亮文本
const highlightText = (text, query) => {
  if (!query || !text) return text
  
  const regex = new RegExp(`(${query})`, 'gi')
  return text.replace(regex, '<span class="highlight">$1</span>')
}
</script>

<style lang="scss" scoped>
.message-list {
  padding: 20px;

  .message-card {
    .card-header {
      margin-bottom: 16px;
    }

    .message-title {
      display: flex;
      align-items: center;
      gap: 8px;

      .message-type {
        flex-shrink: 0;
      }

      .title-text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .message-detail {
    .detail-header {
      margin-bottom: 20px;

      .title-section {
        margin-bottom: 16px;

        h3 {
          margin: 0 0 8px;
          font-size: 18px;
        }

        .meta-info {
          display: flex;
          gap: 8px;

          .status-tag {
            margin-left: 8px;
          }
        }
      }

      .creator-info {
        color: #909399;
        font-size: 14px;

        span {
          margin-right: 16px;
        }
      }
    }

    .detail-content {
      margin-bottom: 20px;
      padding: 16px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .content-text {
        white-space: pre-wrap;
        word-break: break-all;
      }
    }

    .detail-footer {
      .handler-info {
        margin-bottom: 16px;
        color: #909399;
        font-size: 14px;

        span {
          margin-right: 16px;
        }
      }

      .process-records {
        h4 {
          margin: 0 0 16px;
          font-size: 16px;
        }

        .record-content {
          .record-status {
            margin-bottom: 8px;
          }

          .record-comment {
            margin-bottom: 8px;
            color: #606266;
          }

          .record-operator {
            color: #909399;
            font-size: 12px;
          }
        }
      }
    }
  }
}

:deep(.highlight) {
  background-color: #ffd04b;
  padding: 0 2px;
  border-radius: 2px;
}

.user-department {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}
</style> 